home *** CD-ROM | disk | FTP | other *** search
- Path: howland.reston.ans.net!agate!parsons
- From: parsons@vouvray.CS.Berkeley.EDU (David C. Parsons)
- Newsgroups: comp.lang.c++
- Subject: Need help on static data members of class templates
- Date: 17 Mar 1996 05:09:03 GMT
- Organization: University of California, Berkeley
- Message-ID: <4ig6pf$aqp@agate.berkeley.edu>
- NNTP-Posting-Host: vouvray.cs.berkeley.edu
-
- I've been having a lot of difficulty getting static data members of
- class templates to work right. Specifically, things get very weird
- when I try to instantiate the template with the type parameter equal
- to another instantiation of the template. The following is boiled
- down from the code that gives me the problem:
-
- //-- begin code sample --------------------------------
-
- #include <iostream.h>
-
- template< class T >
- class C
- {
- public:
-
- static const T classVar;
- C()
- {
- cout << "instantiating C: classVar is " << classVar << endl;
- i = 100; // this is line 12
- }
- int i;
- }; // end of class C
-
- template< class T >
- ostream& operator <<( ostream& os, const C< T >& c )
- {
- os << "[object of class C having classVar " << c.classVar << "]";
- return os;
- }
-
- // initialize static members of template instantiations we'll need
-
- const int C<int>::classVar = 3;
- const C< int > C< C<int> >::classVar = C<int>(); // this is line 27
-
- int main()
- {
- C< int > c1;
- C< C<int> > c2;
- }
-
- //-- end code sample --------------------------------
-
- This compiles fine under g++ (with only a warning about unused
- variables c1 and c2), but when run it produces:
-
- instantiating C: classVar is 3
- Bus error (core dumped)
-
- From gdb, it appears that the error is occurring during the
- construction of the C< C<int> >::classVar object:
-
- #0 0x4590 in C<int>::C (this=0x36b0) at scratch.C:12
- #1 0x4478 in global constructors keyed to
- C<int>::classVar () at scratch.C:27
- #2 0x1d00c in __do_global_ctors ()
- #3 0x1d050 in __main ()
- #4 0x43a0 in main () at scratch.C:30
-
- Surprisingly (to me at least), the whole problem goes away if I
- comment out the assignment i = 100; in the constructor (line 12
- above). The output is then:
-
- instantiating C: classVar is 3
- instantiating C: classVar is 3
- instantiating C: classVar is [object of class C having classVar 3]
-
- In summary, it seems that assigning to any data member in the
- constructor makes it impossible to instantiate the template with
- another instance of the same template. I do not understand this
- restriction.
-
- I've tried every variation of this code I can think of, but nothing
- seems to work. Anyone have any ideas? I'd really like to get this to
- work, as it forms part of an otherwise very elegant sparse matrix
- package.
-
- David Parsons
-
-
-
-
-
-
-
-
-
-